package com.fc.v2.controller.gen;

import com.fc.v2.common.base.BaseController;
import com.fc.v2.common.domain.AjaxResult;
import com.fc.v2.common.domain.ResultTable;
import com.fc.v2.common.log.Log;
import com.fc.v2.common.support.ConvertUtil;
import com.fc.v2.mapper.auto.FinishProjectMapper;
import com.fc.v2.mapper.auto.FinishUploadMapper;
import com.fc.v2.mapper.auto.TSysRoleUserMapper;
import com.fc.v2.mapper.auto.TsysUserMapper;
import com.fc.v2.model.auto.*;
import com.fc.v2.model.custom.RoleVo;
import com.fc.v2.model.custom.Tablepar;
import com.fc.v2.service.FinishUploadService;
import com.fc.v2.service.SysDepartmentService;
import com.fc.v2.service.SysPositionService;
import com.fc.v2.service.SysUserService;
import com.fc.v2.util.DateUtils;
import com.fc.v2.util.SnowflakeIdWorker;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.unit.DataUnit;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 文件上传Controller
 * @ClassName: FileUploadController
 * @author Archie
 * @date 2019-11-20 22:35
 */
@Api(value = "文件上传")
@Controller
@RequestMapping("/FileUploadController")
public class FileUploadController extends BaseController{

    @Autowired
    private FinishProjectMapper finishProjectMapper;

    @Autowired
    private FinishUploadService finishUploadService;

    @Autowired
    private TsysUserMapper tsysUserMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private TSysRoleUserMapper tSysRoleUserMapper;




    /**
     * 文件上传
     * @param model
     * type=1------总结报告文件上传
     *type=2------项目成果简介文件上传
     * @return String
     * @author Archie
     */
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @RequestMapping(value="/edit/fileImp1/{proId}/{type}",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    // 不返回json数据就要添加ResponseBody标签
    public Map<String,Object> fileImp1(@RequestParam("file") MultipartFile file , HttpServletRequest request,@PathVariable("proId") String proId
                                        ,@PathVariable("type") int type)  {
        //提前写好绝对路径前缀
//        String path = request.getSession().getServletContext().getRealPath("/");
        //指定文件上传的保存路径
        String path = "C:\\_Publish\\社科联";
        File newFile = new File(path, file.getOriginalFilename());
        Map map = new HashMap();
//        System.out.println(file.getOriginalFilename());
//        System.out.println(path);
//        System.out.println(newFile.getPath());
        if(type == 1){
            //添加状态
            //将路径保存在结项文件上传映射表
            FinishUpload finishUpload = new FinishUpload();
            finishUpload.setFinishId(proId);
            finishUpload.setSumUrl(newFile.getPath().replaceAll("\\\\","/"));
            finishUploadService.insertSelective(finishUpload);
            //编辑状态
            //将总结报告文件路径保存
            FinishProject finishProject = new FinishProject();
            finishProject.setId(proId);
            //替换“/“为”\“,用于下载
            finishProject.setSummaryReportUrl(newFile.getPath().replaceAll("\\\\","/"));
            finishProjectMapper.updateByPrimaryKeySelective(finishProject);
        }else if(type == 2){
            //添加状态
            //将路径保存在结项文件上传映射表
            FinishUpload finishUpload = new FinishUpload();
            finishUpload.setFinishId(proId);
            finishUpload.setSumUrl(newFile.getPath().replaceAll("\\\\","/"));
            finishUploadService.insertSelective(finishUpload);
            //编辑状态
            //将项目成果文件路径保存
            FinishProject finishProject = new FinishProject();
            finishProject.setId(proId);
            //替换“/“为”\“,用于下载
            finishProject.setResContentUrl(newFile.getPath().replaceAll("\\\\","/"));
            finishProjectMapper.updateByPrimaryKeySelective(finishProject);
        }else if(type == 3){
            //添加状态
            //将路径保存在结项文件上传映射表
            FinishUpload finishUpload = new FinishUpload();
            finishUpload.setFinishId(proId);
            finishUpload.setDupUrl(newFile.getPath().replaceAll("\\\\","/"));
            finishUploadService.insertSelective(finishUpload);
            //编辑状态
            //将项目成果文件路径保存
            FinishProject finishProject = new FinishProject();
            finishProject.setId(proId);
            //替换“/“为”\“,用于下载
            finishProject.setDupilicateUrl(newFile.getPath().replaceAll("\\\\","/"));
            finishProjectMapper.updateByPrimaryKeySelective(finishProject);
        }else if(type == 4){
            //添加状态
            //将路径保存在结项文件上传映射表
            FinishUpload finishUpload = new FinishUpload();
            finishUpload.setFinishId(proId);
            finishUpload.setFreeCheckUrl(newFile.getPath().replaceAll("\\\\","/"));
            finishUploadService.insertSelective(finishUpload);
            //编辑状态
            //将申请免鉴材料文件路径保存
            FinishProject finishProject = new FinishProject();
            finishProject.setId(proId);
            //替换“/“为”\“,用于下载
            finishProject.setFreeCheckUrl(newFile.getPath().replaceAll("\\\\","/"));
            finishProjectMapper.updateByPrimaryKeySelective(finishProject);
        }else if(type == 5){
            //添加状态
            //将路径保存在结项文件上传映射表
            FinishUpload finishUpload = new FinishUpload();
            finishUpload.setFinishId(proId);
            finishUpload.setProveUrl(newFile.getPath().replaceAll("\\\\","/"));
            finishUploadService.insertSelective(finishUpload);
            //编辑状态
            //将申请免鉴材料文件路径保存
            FinishProject finishProject = new FinishProject();
            finishProject.setId(proId);
            //替换“/“为”\“,用于下载
            finishProject.setProveUrl(newFile.getPath().replaceAll("\\\\","/"));
            finishProjectMapper.updateByPrimaryKeySelective(finishProject);
        }

        try {
            file.transferTo(newFile);
            map.put("msg","OK");
            map.put("code",200);
        } catch (IOException e) {
            e.printStackTrace();
            map.put("msg","erro");
            map.put("code",0);
        }

        return map;
    }

    /**
     * Excel批量导入文件上传
     * @param model
     * @return String
     * @author Archie
     */
    @ApiOperation(value = "文件上传", notes = "文件上传")
    @RequestMapping(value="/excelUpload",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    // 不返回json数据就要添加ResponseBody标签
    public Map<String,Object> excelUpload(@RequestParam("file") MultipartFile file , HttpServletRequest request)  {
        //提前写好绝对路径前缀
//        String path = request.getSession().getServletContext().getRealPath("/");
        //指定文件上传的保存路径
        String path = "C:\\_Publish\\社科联";
        File newFile = new File(path, file.getOriginalFilename());
        Map map = new HashMap();
//        System.out.println(file.getOriginalFilename());
//        System.out.println(path);
//        System.out.println(newFile.getPath());
        try {
            file.transferTo(newFile);
            way(newFile,map);
        } catch (IOException | InvalidFormatException | ParseException e) {
            e.printStackTrace();
            map.put("msg","erro");
            map.put("code",0);
        }

        return map;
    }

    /**
     * 用户Excel文件批量导入数据库
     * @param list
     * @throws IOException
     * @throws InvalidFormatException
     */
    public  void way(File newFile,Map<String,Object> map) throws IOException, InvalidFormatException, ParseException {//传入集合
        List<TsysUser> list = new ArrayList<>();
        Workbook workbook = WorkbookFactory.create(newFile);
        System.out.println("sheets" + workbook.getNumberOfSheets());
        //获取一张表
        Sheet sheet = workbook.getSheetAt(0);
        for (int i = 2; i <= sheet.getLastRowNum(); i++) {//跳过第一行
            Row row = sheet.getRow(i);//取得第i行数据
            if (row == null) {
                break;
            }
            TsysUser userDto = new TsysUser();
            TSysRoleUser tSysRoleUser = new TSysRoleUser();
            String[] str = new String[20];
            for (int j = 0; j < 17; j++) {
                Cell cell = row.getCell(j);//取得第j列数据
                cell.setCellType(CellType.STRING);
                str[j] = cell.getStringCellValue().trim();
                System.out.print(str[j] + " ");
            }
            //System.out.println();
            //封装对象信息
            //用户Id
            String userId = SnowflakeIdWorker.getUUID();
            userDto.setId(userId);
            //登录账号
            userDto.setUsername(str[0]);
            //用户密码
            userDto.setPassword(str[1]);
            //用户姓名
            userDto.setNickname(str[2]);
            //性别
            if(str[3].equals("男")){
                userDto.setUserSex(0);
            }
            if(str[3].equals("女")){
                userDto.setUserSex(1);
            }
            //民族
            userDto.setUserNation(str[4]);
            //职务
            userDto.setUserOffice(str[5]);
            //专业职称
            userDto.setUserTitle(str[6]);
//            学历
            if(str[7].equals("博士")){
                userDto.setUserEducation("g");
            }else if(str[7].equals("硕士")){
                userDto.setUserEducation("f");
            }else if(str[7].equals("本科")){
                userDto.setUserEducation("e");
            }else if(str[7].equals("大专")){
                userDto.setUserEducation("d");
            }else if(str[7].equals("高中")){
                userDto.setUserEducation("c");
            }else if(str[7].equals("初中")){
                userDto.setUserEducation("b");
            }else if(str[7].equals("小学")){
                userDto.setUserEducation("a");
            }
            //学位
            if(str[8].equals("博士")){
                userDto.setUserAcademicDegree("c");
            }else if(str[8].equals("硕士")){
                userDto.setUserAcademicDegree("b");
            }else if(str[8].equals("学士")){
                userDto.setUserAcademicDegree("a");
            }
            //研究专长
            userDto.setUserExpertise(str[9]);
            //电话
            userDto.setUserPhone(str[10]);
            //邮政编码
            userDto.setUserZip(str[11]);
            //单位名称
            userDto.setDeptName(str[12]);
            //银行卡号
            userDto.setUserBankCard(str[13]);
            //开户行
            userDto.setUserBankAddress(str[14]);
            //通讯地址
            userDto.setUserAddress(str[15]);

            //出生年月
//            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
//            Date date = ft.parse(str[16]);
//            userDto.setUserBirth(date);
            //角色
            if(str[16].equals("专家")){
                tSysRoleUser.setId(SnowflakeIdWorker.getUUID());
                tSysRoleUser.setSysUserId(userId);
                tSysRoleUser.setSysRoleId("615413901659607040");
                tSysRoleUserMapper.insertSelective(tSysRoleUser);
            }else if(str[16].equals("单位管理")){
                tSysRoleUser.setId(SnowflakeIdWorker.getUUID());
                tSysRoleUser.setSysUserId(userId);
                tSysRoleUser.setSysRoleId("620402533122314240");
                tSysRoleUserMapper.insertSelective(tSysRoleUser);
            }else if(str[16].equals("单位申报")){
                tSysRoleUser.setId(SnowflakeIdWorker.getUUID());
                tSysRoleUser.setSysUserId(userId);
                tSysRoleUser.setSysRoleId("620402627791949824");
                tSysRoleUserMapper.insertSelective(tSysRoleUser);
            }else if(str[16].equals("社科联管理")){
                tSysRoleUser.setId(SnowflakeIdWorker.getUUID());
                tSysRoleUser.setSysUserId(userId);
                tSysRoleUser.setSysRoleId("620402700860919808");
                tSysRoleUserMapper.insertSelective(tSysRoleUser);
            }
            //添加时间
            userDto.setUpdateTime(new Timestamp(new Date().getTime()));
            //加入到集合中
            list.add(userDto);
        }

        //将集合写入数据库
        System.out.println("添加数据大小为：" + list.size());
//        TsysUserExample tsysUserExample = new TsysUserExample();
        int i = 0;
        for (TsysUser tsysUser : list) {
//            tsysUserExample.createCriteria().andUsernameEqualTo(tsysUser.getUsername());
//            TsysUser db_user = tsysUserMapper.selectByExample(tsysUserExample).get(0);
//            if (db_user != null) {
//                System.out.println(db_user.getId() + " " + tsysUser.getUsername() + " " + tsysUser.toString() + " 已存在此用户！");
//                continue;
//            }
            tsysUserMapper.insertSelective(tsysUser);
            i++;
        }
        if(i==list.size()){
            map.put("msg","OK");
            map.put("code",200);
        }else{
            map.put("msg","erro");
            map.put("code",0);
        }
    }





    /**
     * 附件下载
     *
     * @param request
     * @param response
     */
    @RequestMapping("/downloadTwo")
    public void downloadFileTwo( HttpServletRequest request, HttpServletResponse response) {

        String fileName = request.getParameter("fileName");
        String downUrl = request.getParameter("downUrl");

        goToDownload(request, response, downUrl, fileName);

    }

    /**
     * 下载
     *
     * @param request
     * @param response
     * @param downUrl  下载的路径
     * @param fjmc     下载文件的名称
     */
    private void goToDownload(HttpServletRequest request, HttpServletResponse response, String downUrl, String fjmc) {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/x-msdownload");
        try {
            String encodenickname = URLEncoder.encode(fjmc,"UTF-8");//转Unicode不然ie会乱码
            response.setHeader("Content-Disposition", "attachment;fileName=" + new String(encodenickname.getBytes("UTF-8"), "ISO8859-1"));
            //这里注掉的代码是本地测试的
//            String path = request.getSession().getServletContext().getRealPath("/");
//            String ATTACH_PATH= AppConfig.getInstance().getProperty("attach.base","");
//            if (StringUtils.isNotEmpty(ATTACH_PATH)) {
//                path = ATTACH_PATH;
//            }
//            logger.debug("=path===" + path);
            File file = new File( downUrl);
            if (!file.exists()) {
                response.sendError(404, "File not found!");
                return;
            }
            long fileLength = file.length();
            response.setHeader("Content-Length", String.valueOf(fileLength));
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[2048];
            int bytesRead;
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
            }
            bis.close();
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
